// 云函数入口文件
const cloud = require('wx-server-sdk')
const md5 = require('md5-node')

cloud.init()


const db = cloud.database();
const collectTable = db.collection('gas_collect');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  const wxContext = cloud.getWXContext()
  try {
    const countResult = await collectTable.count()
    const total = countResult.total
    const res = total ? await collectTable.where({
      '_id': _.eq(md5(wxContext.OPENID))
    }).get():null;
    if ( res.data.length==0) {//没有记录，新增
      console.log('没有记录')

      return await collectTable.add({
        data: {
          _id: md5(wxContext.OPENID),
          openid: wxContext.OPENID,
          gasList: [event.stationId]
        }
      })
    } else {
      console.log('有记录') 
      let arr = res.data[0].gasList
      console.log(arr)
      let has = false;
      for (let i = 0; i < arr.length; i++){
        if (arr[i] === event.stationId){
          has = true
          arr.splice(i,1)
          console.log('收藏过')
        } 
      }

      console.log(has)
      console.log(arr)


      if(has){ //取消收藏
        let cancelRes = await collectTable.doc(md5(wxContext.OPENID)).update({
          data: {
            gasList: _.set(arr)
          }
        })
        if (cancelRes){
          return {
            code: 200,
            msg:'已取消关注'
          }
        }
      }else{ //添加收藏
        let successRes = await collectTable.doc(md5(wxContext.OPENID)).update({
          data: {
            gasList: _.push(event.stationId)
          }
        })
        if (successRes) {
          return {
            code: 200,
            msg: '已经关注'
          }
        }
      }

    }
  } catch (err) {
    console.error(err)
  }
}